package cn.edu.whu.forecast.controller;

import cn.edu.whu.forecast.cache.CacheEntity;
import cn.edu.whu.forecast.cache.CacheManagerImpl;
import cn.edu.whu.forecast.common.PageBean;
import cn.edu.whu.forecast.common.ResultBean;
import cn.edu.whu.forecast.entity.mysql.UserInfo;
import cn.edu.whu.forecast.enums.ResultCode;
import cn.edu.whu.forecast.service.impl.UserServiceImpl;
import cn.edu.whu.forecast.util.JwtUtil;
import cn.edu.whu.forecast.util.ValidateCode;
import cn.edu.whu.forecast.vo.response.UserVo;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@Api(tags = "用户管理")
@RequestMapping("/user")
@CrossOrigin
public class UserController {
    @Resource
    private UserServiceImpl userService;

    @Resource
    private CacheManagerImpl cacheManager;

    //  获取图片验证码
    @GetMapping("/code")
    public String generateCode(){
//      实例化验证码工具类
        ValidateCode validateCode = new ValidateCode();
//      生成图片（base64格式）
        String base64Img = validateCode.getRandomCodeBase64();

        /*
          将验证码对应的字符存储至sessinon中，注意由于跨域问题，sessionid默认无法共享，需要加入跨域配置
          具体配置参考：config/WebMvcConfigurer类
          前端在发送请求时，也需要设置参数: withCredentials：true
          axios.get("http://localhost/xxx",{withCredentials:true}).then(res=>{

          })
         */
        //cacheManager.put("code",new CacheEntity(validateCode.getCode(),1000*60*10L, System.currentTimeMillis()));
        cacheManager.put("code", validateCode.getCode(),1000*60*10L);
        return base64Img;
    }


    @GetMapping("/getAllUser")
    public PageBean<UserInfo> getAllUser(
            @RequestParam("pageNum") int pageNum,
            @RequestParam("pageSize") int pageSize
    ){
        return userService.getAllUser(pageNum,pageSize);
    }

    @PostMapping("/addUser")
    public ResultBean<?> addUser(
        @RequestParam("name") String name,
        @RequestParam("username") String username,
        @RequestParam("password") String password,
        @RequestParam("role") Boolean role
    ){
        List<UserInfo> allUser = userService.getAllUser();
        for(UserInfo userInfo:allUser){
            if(userInfo.getUsername().equals(username)){
                return ResultBean.fail(ResultCode.UserAlreadyExist);
            }
        }
        userService.addUser(name, username, password, role);
        return ResultBean.ok();
    }

    @PostMapping("/deleteUser")
    public ResultBean<?> deleteUser(
            @RequestParam("id") Integer id
    ){
        userService.delUser(id);
        return ResultBean.ok();
    }

    @PostMapping("/updateUser")
    public ResultBean<?> updateUser(
            @RequestParam("id") Integer id,
            @RequestParam("name") String name,
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("role") Boolean role
    ){
        UserInfo user = userService.getUser(id);
        user.setName(name);
        user.setUsername(username);
        user.setPassword(password);
        user.setRole(role);
        userService.updateUser(user);
        return ResultBean.ok();
    }

    @PostMapping("/login")
    public ResultBean<?> login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("code") String code
    ){

        if(!code.equalsIgnoreCase((String) cacheManager.getCacheByKey("code").getData())){
            return ResultBean.fail(ResultCode.VerificationCodeError);
        }else{
            UserVo userVo = new UserVo();

            List<UserInfo> allUser = userService.getAllUser();
            for(UserInfo userInfo:allUser){
                if(userInfo.getUsername().equals(username)&&userInfo.getPassword().equals(password)){
                    userVo.setToken(JwtUtil.createToken(userInfo));
                    userVo.setUsername(username);
                    userVo.setRole(userInfo.getRole());
                    return ResultBean.ok(userVo);
                }
            }
        }
        return ResultBean.fail(ResultCode.UserLoginVerifyFail);
    }

    @GetMapping("/checkToken")
    public ResultBean<?> checkToken(HttpServletRequest request){
        String token = request.getHeader("token");
        if(JwtUtil.checkToken(token)){
            return ResultBean.ok();
        }
        return ResultBean.fail(ResultCode.Unauthorized);
    }


    @RequestMapping("/logout")
    public ResultBean<?> logout(HttpSession session){
        session.invalidate();
        return ResultBean.ok();
    }
}
